package com.github.postsanf.yinian.fragment;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LocalAlbumAdapter;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class LocalAlbumFragment extends BaseFragment {
    private ListView mListDir;
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private Context mContext;
    private ProgressDialog mProgressDialog;                // 进度条
    private HashSet<String> mDirPaths = new HashSet<String>();
    private int totalCount;
    private int mPicsSize;                        // 文件夹图片数量
    private File mImgDir;                        // 图片数量最多的文件夹
    private LocalAlbumAdapter localAlbumAdapter;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mProgressDialog.dismiss();
                if (mImageFloders.size() > 0) {
                    localAlbumAdapter = new LocalAlbumAdapter(mContext, mImageFloders);
                    mListDir.setAdapter(localAlbumAdapter);
                }
            }
        }
    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity();
        View view = View.inflate(getActivity(), R.layout.yn_fragment_localbum, null);
        mListDir = (ListView) view.findViewById(R.id.rv_local_album);
        getImages();
        return view;
    }


    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getActivity(), "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(mContext, "", CommonConstants.TIP_LOAD_DATA);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = mContext
                        .getContentResolver();
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);
//				Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;

                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;

                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (!StringUtils.isEmpty(dirPath) && mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".gif") || filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });

                    int picSize = (pics != null) ? pics.length : 0;
                    totalCount += picSize;

                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }
}